package com.dream.myqiyi.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiInfo;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.dream.myqiyi.BaseApp;
import com.dream.myqiyi.Global;
import com.dream.myqiyi.R;
import com.dream.myqiyi.AsyncImageLoader.ImageCallback;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.dao.NoteResourceModel;
import com.dream.myqiyi.image.ui.AlbumListActivity;
import com.dream.myqiyi.paint.TuyaActivity;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteResourceService;
import com.dream.myqiyi.service.NoteService;
import com.dream.myqiyi.service.NotebookService;
import com.dream.myqiyi.service.TagService;
import com.dream.myqiyi.ui.RecorderPopup.OnCloseListener;
import com.dream.myqiyi.util.StringUtils;
import com.dream.myqiyi.web.ui.activities.WebMainActivity;
import com.dream.myqiyi.widget.Effect;
import com.dream.myqiyi.widget.RichEditText;
import com.dream.myqiyi.widget.RichEditText.OnSelectionChangedListener;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class NoteViewActivity extends MapActivity  {

	public static final int IMAGE_SELECTED_RESULT = 100;
	public static final int CAMERA_SELECTED_RESULT = 101;
	public static final int RECORDER_SELECTED_RESULT = 102;
	public static final int INFO_RESULT = 103;
	public static final int IMAGE_EDIT_RESULT = 104;
	public static final int MAP_IMAGE_RESULT = 105;
	public static final int WEB_IMAGE_RESULT = 106;
	public static final int RECORDER_VIEW_RESULT = 107;
	public static final int HYPERLINK_RESULT = 108;

    private EditText mNotetitle;
    private Gallery resGallery;
    private ImageAdapter resAdapter;
    private ArrayList<String> resGuids;
    private RichEditText mNoteContentEdit;
    private WebView mNoteContentView;
    private Handler handler = new Handler();
    
    private String noteGuid;
    private NoteModel note;
    private boolean isEditMode = false;

    private int noteType;
    private String notebookGuid;
    private String tagGuid;
    
    boolean isCreate;
    String strBefore;
    private Button retBtn;
    private Button saveBtn;
    private Button imgBtn;
    private Button soundBtn;
    private Button editBtn;
    private Button resBtn;

    // 底部编辑menu
    private LinearLayout mBottomEditLayout;
    private CheckBox mBoldChk;
    private CheckBox mItalicChk;
    private CheckBox mUnderlineChk;
    private CheckBox mStrikeChk;
    private CheckBox mBgColorChk;    
    
    //private LinearLayout mBottomViewLayout;

    // 相机相关
	private File mCurrentPhotoFile;

	private PopMenu popMenu;
	private PopMenu popMenuShare;
	
	private boolean isRecord = false;

	// 经纬度
	private double latitude = 0.0;
	private double longitude =0.0;
	private String address = "";
	// 定义地图引擎管理类  
    private BMapManager mapManager;  
    // 定义搜索服务类  
    private MKSearch mMKSearch; 

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_view_activity);

		initUI();
		
		initUIData();
	}
	
	@Override  
    protected void onDestroy() {  
        if (mapManager != null) {  
            // 程序退出前需调用此方法  
            mapManager.destroy();  
            mapManager = null;  
        }  
        super.onDestroy();  
    }  
  
    @Override  
    protected void onPause() {  
        if (mapManager != null) {  
            // 终止百度地图API  
            mapManager.stop();  
        }  
        super.onPause();  
    }  
  
    @Override  
    protected void onResume() {  
        if (mapManager != null) {  
            // 开启百度地图API  
            mapManager.start();  
        }  
        super.onResume();  
    }  
    
	private void initUIData() {
		
		mapManager = new BMapManager(getApplication());
		mapManager.init(Global.BMAP_KEY, null);
		super.initMapActivity(mapManager);
		
		mMKSearch = new MKSearch();
		mMKSearch.init(mapManager, new MySearchListener());
		
		// 获取GPS信息
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				GetGpsInfo();
			}
		});
		
		Bundle bundle = this.getIntent().getExtras();
		NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
		NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");

		notebookGuid = nbSrv.getCurrNotebook().getGuid();
		noteGuid = bundle.getString("note_guid");
		if (StringUtils.isNull(noteGuid)) {
			// 新建note
			noteType = bundle.getInt("note_type");
			switch (noteType) {
			case NoteListActivity.NOTEBOOK_TYPE:
				notebookGuid = bundle.getString("guid");
				tagGuid = "";
			case NoteListActivity.TAG_NOTE_TYPE:
				notebookGuid = "";
				tagGuid = bundle.getString("guid");
				break;
			}
			note = new NoteModel();
			note.setCreated(new Date().getTime());
			note.setUpdated(new Date().getTime());
			note.setGuid(Global.getGuid());
			if (StringUtils.isNull(notebookGuid)) {
				note.setNotebookGuid(noteGuid);
			}
			
			isEditMode = true;
		} else {
			note = noteSrv.getNote(noteGuid);
			isEditMode = false;
		}
		noteSrv.setCurrNoteModel(note);
		
		String newMode = bundle.getString("new_mode");
		if (newMode != null) {
			isEditMode = true;
			if (newMode.equals("camera")) {
				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				mCurrentPhotoFile = new File(Global.getPhotoFileName());
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
				startActivityForResult(intent, CAMERA_SELECTED_RESULT);
			} else if (newMode.equals("recorder")) {
				//　TODO　
				isRecord = true;
			}				
		}
		
		if (note.getAttributeLatitude() == 0.0 && note.getAttributeLongitude() == 0.0) {
			new GetAddressTask().execute("");
		}
		
		resGuids = new ArrayList<String>();
		
		Global.clearResIndex();
		
		setNoteMode(isEditMode);
	}
	
	private void setNoteMode(boolean isEdit) {
		isEditMode = isEdit;
		if (isEditMode) {
		    mNoteContentEdit.setVisibility(View.VISIBLE);
		    mBottomEditLayout.setVisibility(View.VISIBLE);
		    saveBtn.setVisibility(View.VISIBLE);
		    retBtn.setVisibility(View.GONE);
		    imgBtn.setVisibility(View.VISIBLE);
		    soundBtn.setVisibility(View.VISIBLE);
		    mNoteContentView.setVisibility(View.GONE);
		    editBtn.setVisibility(View.GONE);
		    resBtn.setVisibility(View.VISIBLE);
		    resGallery.setVisibility(View.GONE);
		    
		    // TODO 将资源从字符串中取出来
		    
		    mNoteContentEdit.setText(Html.fromHtml(note.getContent(), imageGetter, null));
		    
		    Document document = Jsoup.parse(note.getContent());
			Elements resElems = document.body().getElementsByTag("img");
			Iterator<Element> resIt = resElems.iterator();
			while (resIt.hasNext()) {
				Element resElem = resIt.next();
				String guid = resElem.attr("src");
				if (!StringUtils.isNull(guid)) {
					resGuids.add(Global.getFileNameNoEx(guid));
				}
				//resElem.remove();
			}
			
		    showRes(resGallery.getVisibility() == View.VISIBLE);
		    
		} else {
		    mNoteContentEdit.setVisibility(View.GONE);
		    mBottomEditLayout.setVisibility(View.GONE);
		    imgBtn.setVisibility(View.GONE);
		    soundBtn.setVisibility(View.GONE);
		    mNoteContentView.setVisibility(View.VISIBLE);
		    editBtn.setVisibility(View.VISIBLE);
		    retBtn.setVisibility(View.VISIBLE);
		    saveBtn.setVisibility(View.GONE);
		    resBtn.setVisibility(View.GONE);
		    resGallery.setVisibility(View.GONE);

		    showRes(resGallery.getVisibility() == View.VISIBLE);
		    
		    mNoteContentView.loadDataWithBaseURL(Global.resDirWeb, note.getContent(), "text/html", "UTF-8", null) ;
		    
		}
	}
	
	private void initUI() {
		isCreate = false;
		RelativeLayout layout = (RelativeLayout)this.findViewById(R.id.note_layout);
		layout.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
		    public boolean onPreDraw() {
		        //这里坐标已经确定了
//		    	if (!isCreate) {
//		    		if (note != null) {
//						mNotetitle.setText(note.getTitle());
//						//mNoteContentEdit.setText(Html.fromHtml(note.getContent(), null, ResTagHandler));
//		    		}
//		    		if (!StringUtils.isNull(strBefore)) {
//		    			//final int selectedIndex = mNoteContent.getSelectionStart();
//		    			Editable editable = mNoteContentEdit.getEditableText();
//	    				editable.append(Html.fromHtml("<img src='"+ strBefore +"'/>", imageGetter, null));
//		    		}
//		    		isCreate = true;
//		    	}
		    	
		    	if (isRecord) {
		    		isRecord = false;
					final String recordFilename = Global.getRecorderFileName();
					RecorderPopup popup = new RecorderPopup(NoteViewActivity.this, recordFilename);
					popup.setOnCloseListener(new OnCloseListener() {
						@Override
						public void onClose(int length) {
							addNoteResFile(recordFilename);
						}
					});
					popup.showAtLocation(findViewById(R.id.note_layout), Gravity.TOP, 0, 75);

		    	}
		    	return true;
		    }
		});
		popMenu = new PopMenu(NoteViewActivity.this);
		popMenu.addItems(new String[] { "拍摄照片", "选择图片", "在地图上绘制", "从网页上抓取" });
		// 菜单项点击监听器
		popMenu.setOnItemClickListener(popmenuItemClickListener);

		popMenuShare = new PopMenu(NoteViewActivity.this);
		popMenuShare.addItems(new String[] { "发送邮件", "微博分享", "微信分享" });
		// 菜单项点击监听器
		popMenuShare.setOnItemClickListener(popmenuItemShareClickListener);
		
		resGuids = new ArrayList<String>();
		resAdapter = new ImageAdapter(this, resGuids);
		resGallery = (Gallery) findViewById(R.id.resGallery);
		resGallery.setVisibility(View.GONE);
		resGallery.setAdapter(resAdapter);
		resGallery.setOnItemClickListener(new OnItemClickListener() {		 
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				NoteResourceService nrSrv = (NoteResourceService) ApplicationContext.getSingleton().getBean("NoteResourceService");
				NoteResourceModel nrm = nrSrv.getNoteResource(resGuids.get(position));
				if (nrm != null) {
					int resType = Global.getResFileType(nrm.getAttributeFileName()); 
					if (resType == Global.RES_TYPE_IMAGE) {
						viewImage(nrm.getAttributeFileName());
					} else if (resType == Global.RES_TYPE_SOUND) {
						viewSound(nrm.getAttributeFileName());
					}
				}
				//显示点击的是第几张图片
				//Toast.makeText(MainHelloGallery.this, "" + position,
					//	Toast.LENGTH_LONG).show();
				//设置背景部分的ImageView显示当前Item的图片
				//iv.setImageResource(((ImageView)view).getId());
			}
		});
		
		mNotetitle = (EditText) this.findViewById(R.id.noteTitleTextView);
		mNotetitle.clearFocus();
		mNoteContentEdit = (RichEditText) this.findViewById(R.id.noteTextView);
//		mNoteContentEdit.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//			    // 点击图片
//			    Spanned s = mNoteContentEdit.getText();  
//			    ImageSpan[] imageSpans = s.getSpans(0, s.length(), ImageSpan.class);  
//			    int selectionStart = mNoteContentEdit.getSelectionStart();  
//			    for (ImageSpan span : imageSpans) {  
//			    	int start = s.getSpanStart(span);  
//			    	int end = s.getSpanEnd(span);  
//			    	if (selectionStart >= start && selectionStart < end) {
//			    		//找到图片  
//			    		String src = span.getSource();
//			    		String srcExt = Global.getFileExName(src);
//			    		if (srcExt.equals("png") || srcExt.equals("jpg") || srcExt.equals("jpeg")) {
//			    			viewImage(src);
//			    		} else {
//			    			viewSound(src);
//			    		}
//			    		return; 
//			    	}
//			    }  
//			}
//		});
		mNoteContentEdit.setOnSelectionChangedListener(new OnSelectionChangedListener() {
			@Override
			public void onSelectionChanged(int start, int end, List<Effect<?>> effects) {
			    mBoldChk.setChecked(false);
			    mItalicChk.setChecked(false);
			    mUnderlineChk.setChecked(false);
			    mStrikeChk.setChecked(false);
			    mBgColorChk.setChecked(false);

				for (Effect<?> e : effects) {
					if (e == RichEditText.BOLD) {
						mBoldChk.setChecked(true);
					} else if (e == RichEditText.ITALIC) {
						mItalicChk.setChecked(true);
					} else if (e == RichEditText.UNDERLINE) {
						mUnderlineChk.setChecked(true);
					} else if (e == RichEditText.STRIKETHROUGH) {
						mStrikeChk.setChecked(true);
					} else if (e == RichEditText.BACKGROUNDCOLOR) {
						mBgColorChk.setChecked(true);
					}
				}
			}
		});
		
		mNoteContentView = (WebView)this.findViewById(R.id.noteWebView);
		WebSettings settings = mNoteContentView.getSettings();
		settings.setDefaultTextEncodingName("UTF-8") ;
		settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		
		// 顶部菜单
        retBtn = (Button) this.findViewById(R.id.note_return_btn);
        retBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
					
					// 返回原来的界面
					Intent intent = null;
					Bundle bundle = null;
					switch (noteType) {
					case NoteListActivity.ALL_NOTE_TYPE:
						intent = new Intent(NoteViewActivity.this, NoteListActivity.class);
						break;
					case NoteListActivity.NOTEBOOK_TYPE:
						// 从notebook创建
						bundle = new Bundle();
						bundle.putInt("note_type", NoteListActivity.NOTEBOOK_TYPE);
						bundle.putString("guid", notebookGuid);
						intent = new Intent(NoteViewActivity.this, NoteListActivity.class);
						intent.putExtras(bundle);
						break;
					case NoteListActivity.TAG_NOTE_TYPE:
						bundle = new Bundle();
						bundle.putInt("note_type", NoteListActivity.TAG_NOTE_TYPE);
						bundle.putString("guid", tagGuid);
						intent = new Intent(NoteViewActivity.this, NoteListActivity.class);
						intent.putExtras(bundle);
						break;
					case NoteListActivity.MAIN_TYPE:
						intent = new Intent(NoteViewActivity.this, MainActivity.class);
						break;
					}
	    				
					if (intent != null) {
						startActivity(intent);
						NoteViewActivity.this.finish();
					}
				
			}
        });
        saveBtn = (Button) this.findViewById(R.id.note_save_btn);
        saveBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 自动保存
				if (mNotetitle.getText().toString() != "" || mNoteContentEdit.getText().toString() != "") {
					note.setTitle(mNotetitle.getText().toString());
					note.setContent(Html.toHtml(mNoteContentEdit.getText()));
					note.setAttributeLatitude(latitude);
					note.setAttributeLongitude(longitude);
						
					new SaveNoteTask().execute("");
				}
				setNoteMode(false);
				
			}

        });
        editBtn = (Button) this.findViewById(R.id.note_edit_btn);
        editBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				resGuids.clear();
				setNoteMode(true);				
			}        	
        });
        resBtn = (Button) this.findViewById(R.id.note_res_btn);
        resBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (resGallery.getVisibility() == View.GONE) {
					resGallery.setVisibility(View.VISIBLE);
					resAdapter.setResource(resGuids);
					resAdapter.notifyDataSetChanged();
					updateNoteImage();
				} else {
					resGallery.setVisibility(View.GONE);
					updateNoteImage();
				}
			}
        });

        imgBtn = (Button) this.findViewById(R.id.note_image_btn);
        imgBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)
						mNoteContentEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

				popMenu.showAsDropDown(v);
			}
        });
        soundBtn = (Button) this.findViewById(R.id.note_sound_btn);
        soundBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)
						mNoteContentEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

				final String recordFilename = Global.getRecorderFileName();
				RecorderPopup popup = new RecorderPopup(NoteViewActivity.this, recordFilename);
				popup.setOnCloseListener(new OnCloseListener() {

					@Override
					public void onClose(int length) {
						// TODO 增加声音
						String guid = Global.getFileNameNoEx(recordFilename);
						new SaveResourceTask().execute(guid, noteGuid, recordFilename);

						addNoteResFile(recordFilename);
					}
					
				});
				popup.showAtLocation(findViewById(R.id.note_layout), Gravity.TOP, 0, 75);
			}
        });
        Button infoBtn = (Button) this.findViewById(R.id.note_info_btn);
        infoBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)
						mNoteContentEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

				Intent intent = new Intent (NoteViewActivity.this, NoteInfoActivity.class);
				startActivityForResult(intent, INFO_RESULT);
			}

        });
        Button shareBtn = (Button) this.findViewById(R.id.note_share_btn);
        shareBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)
						mNoteContentEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

				popMenuShare.showAsDropDown(v);

			}

        });

        // 底部编辑menu
        initBottomUI();

	}
	
	
	private void viewImage(String file) {
		file = Global.resDir + file;
    	Intent intent = new Intent (NoteViewActivity.this, TuyaActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("image_file", file);
		intent.putExtras(bundle);
		startActivityForResult(intent, IMAGE_EDIT_RESULT);				
	}

	private void viewSound(String file) {
		file = Global.resDir + file;
		PlayerPopup popup = new PlayerPopup(NoteViewActivity.this, file);
		popup.showAtLocation(findViewById(R.id.note_layout), Gravity.TOP, 0, 75);
	}

	private void initBottomUI() {
		// 视图底部菜单
//		mBottomViewLayout = (LinearLayout)findViewById(R.id.note_view_bottom_view_layout);
//		findViewById(R.id.to_edit_btn).setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				setNoteMode(true);
//			}
//		});
		
		// 编辑底部菜单
		mBottomEditLayout = (LinearLayout)findViewById(R.id.note_view_bottom_edit_layout);
        
        // 文字格式
        mBoldChk = (CheckBox)findViewById(R.id.bold_btn);
        mBoldChk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				mNoteContentEdit.doAction(RichEditText.FMT_BOLD);
			}        	
        });
        mItalicChk = (CheckBox)findViewById(R.id.italic_btn);
        mItalicChk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				mNoteContentEdit.doAction(RichEditText.FMT_ITALIC);
			}        	
        });
        mUnderlineChk = (CheckBox)findViewById(R.id.underline_btn);
        mUnderlineChk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				mNoteContentEdit.doAction(RichEditText.FMT_UNDERLINE);
			}        	
        });
        mStrikeChk = (CheckBox)findViewById(R.id.strike_btn);
        mStrikeChk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				mNoteContentEdit.doAction(RichEditText.FMT_STRIKETHROUGH);
			}        	
        });
        mBgColorChk = (CheckBox)findViewById(R.id.bgcolor_btn);
        mBgColorChk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				mNoteContentEdit.doAction(RichEditText.FMT_SUBSCRIPT);
			}        	
        });        
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Bundle bundle = null;
		switch (requestCode) {
		case IMAGE_SELECTED_RESULT: //选择图片返回
			bundle = data.getExtras();
			String result = bundle.getString("select_result");
			if (result.equals("selected")) {
				String imageFile = bundle.getString("image_file");
				String guid = Global.getGuid();
				new SaveOuterResourceTask().execute(guid, noteGuid, imageFile);
				addNoteResFile(guid + ".png");
			}
			break;
		case CAMERA_SELECTED_RESULT:	// 相机返回
			if (mCurrentPhotoFile != null && mCurrentPhotoFile.exists()) {
				String guid = Global.getFileNameNoEx(mCurrentPhotoFile.getAbsolutePath());
				new SaveResourceTask().execute(guid, noteGuid, mCurrentPhotoFile.getAbsolutePath());
				addNoteResFile(Global.getFileNameWithEx(mCurrentPhotoFile.getAbsolutePath()));
			}
			break;
		case IMAGE_EDIT_RESULT:	// 图片编辑返回
			bundle = data.getExtras();
			String resultEdit = bundle.getString("edit_result");
			if (resultEdit.equals("modify")) {
				String file = bundle.getString("image_file");
				String guid = Global.getFileNameNoEx(file);
				Global.asyncImageLoader.removeCache(guid);
				new SaveResourceTask().execute(guid, noteGuid, file);

				updateNoteImage();
			}
				//nrSrv.saveNoteResource();
//			}
			break;
		case RECORDER_SELECTED_RESULT: // 录音返回
			bundle = data.getExtras();
			String recordResult = bundle.getString("select_result");
			if (recordResult.equals("record")) {
				String soundFile = bundle.getString("sound_file");
				String guid = Global.getFileNameNoEx(soundFile);
				new SaveResourceTask().execute(guid, noteGuid, soundFile);
				addNoteResFile(soundFile);
			}
			break;
		case RECORDER_VIEW_RESULT: // 播放录音返回
			break;

		case MAP_IMAGE_RESULT:
			bundle = data.getExtras();
			String mapResult = bundle.getString("map_result");
			if (mapResult.equals("selected")) {
				String imageFile = bundle.getString("map_file");
				String guid = Global.getFileNameNoEx(imageFile);
				new SaveResourceTask().execute(guid, noteGuid, imageFile);
				addNoteResFile(imageFile);
			}
			break;
		case WEB_IMAGE_RESULT:
			bundle = data.getExtras();
			String webResult = bundle.getString("web_result");
			if (webResult.equals("selected")) {
				String imageFile = bundle.getString("web_file");
				String guid = Global.getFileNameNoEx(imageFile);
				new SaveResourceTask().execute(guid, noteGuid, imageFile);
				addNoteResFile(imageFile);
			}
			break;
		case INFO_RESULT:
			break;
		case HYPERLINK_RESULT: // 创建超链接
			bundle = data.getExtras();
			String hyperUrl = bundle.getString("hyper_url");
			if (!hyperUrl.equals("")) {
				String hyperName = bundle.getString("hyper_name");
				addHyperlink(hyperUrl, hyperName);
			}
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private class SaveResourceTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			NoteResourceService nrSrv = (NoteResourceService)ApplicationContext.getSingleton().getBean("NoteResourceService");
			if (nrSrv != null) {
				nrSrv.saveNoteResource(params[0], params[1], params[2]);
			}
			return null;
		} 
	};
	
	private class SaveOuterResourceTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {

			NoteResourceService nrSrv = (NoteResourceService)ApplicationContext.getSingleton().getBean("NoteResourceService");
			if (nrSrv != null) {
				String imageDst = Global.resDir + params[0] + ".png";
					Global.changeImage(params[2], imageDst);
					nrSrv.saveNoteResource(params[0], params[1], imageDst);
			}
			return null;
		} 
	};

	private void showRes(boolean isShow) {
		if (!isShow) {
			resGallery.setVisibility(View.GONE);
		} else {
			if (resGuids.size() == 0) {
				resGallery.setVisibility(View.GONE);
			} else {
				resGallery.setVisibility(View.VISIBLE);
				resAdapter.setResource(resGuids);
				resAdapter.notifyDataSetChanged();
			}			
		}
	}
	
	private void addNoteResFile(final String file) {
		resGuids.add(Global.getFileNameNoEx(file));
		
		final int selectedIndex = mNoteContentEdit.getSelectionStart();
		Editable editable = mNoteContentEdit.getEditableText();
		String imgHtml = "<img src=\""+ Global.getFileNameWithEx(file) +"\"/><br>";
		if (selectedIndex < 0) {
			editable.append(Html.fromHtml(imgHtml, imageGetter, null));
		} else {
			editable.insert(selectedIndex, Html.fromHtml(imgHtml, imageGetter, null));
		}
		
		//String html = Html.toHtml(mNoteContentEdit.getText());

		showRes(resGallery.getVisibility() == View.VISIBLE);
	}
	
	private void addNoteSoundFile(final String file) {
		resGuids.add(Global.getFileNameNoEx(file));
		
		String imgHtml = "<img src=\""+ Global.getFileNameWithEx(file) +"\"/><br>";
		final int selectedIndex = mNoteContentEdit.getSelectionStart();
		Editable editable = mNoteContentEdit.getEditableText();
		if (selectedIndex < 0) {
			editable.append(Html.fromHtml(imgHtml, imageGetter, null));
		} else {
			editable.insert(selectedIndex, Html.fromHtml(imgHtml, imageGetter, null));
		}
		
		//String html = Html.toHtml(mNoteContentEdit.getText());

		showRes(resGallery.getVisibility() == View.VISIBLE);
	}

	private void updateNoteImage() {
		String content = Html.toHtml(mNoteContentEdit.getText());
		mNoteContentEdit.setText(Html.fromHtml(content, imageGetter, null));
	}
	
	private void addHyperlink(String hyperUrl, String hyperName) {
		// TODO 在当前位置增加一个超链接
		final int selectedIndex = mNoteContentEdit.getSelectionStart();
		
		String hyperHtml;
		if (hyperName.equals("")) {
			hyperHtml = "<a href=" + hyperUrl + ">" + hyperUrl + "</a>";
		} else {
			hyperHtml = "<a href=" + hyperUrl + ">" + hyperName + "</a>";
		}
		Editable editable = mNoteContentEdit.getEditableText();
		if (selectedIndex < 0) {
			editable.append(Html.fromHtml(hyperHtml));
		} else {
			editable.insert(selectedIndex, Html.fromHtml(hyperHtml));
		}
	}

	// 弹出菜单监听器
	OnItemClickListener popmenuItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// 关闭ime，打开格式编辑面板
			InputMethodManager imm = (InputMethodManager)
					mNoteContentEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

			Intent intent = null;
			switch (position) {
			case 0:
				intent = new Intent("android.media.action.IMAGE_CAPTURE");
				mCurrentPhotoFile = new File(Global.getPhotoFileName());
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
				startActivityForResult(intent, CAMERA_SELECTED_RESULT);

				break;
			case 1:
				// 打开图片选择
				intent = new Intent (NoteViewActivity.this, AlbumListActivity.class);
				startActivityForResult(intent, IMAGE_SELECTED_RESULT);
				break;
			case 2:
				intent = new Intent (NoteViewActivity.this, BMapActivity.class);
				startActivityForResult(intent, MAP_IMAGE_RESULT);
				break;
			case 3:
				intent = new Intent (NoteViewActivity.this, WebMainActivity.class);
				startActivityForResult(intent, WEB_IMAGE_RESULT);
				break;
			}
			//System.out.println("下拉菜单点击" + position);
			popMenu.dismiss();
		}
	};
	OnItemClickListener popmenuItemShareClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// 关闭ime，打开格式编辑面板
			InputMethodManager imm = (InputMethodManager)
					mNoteContentEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

			switch (position) {
			case 0:
				BaseApp.showToast("暂未开放");
				break;
			case 1:
				BaseApp.showToast("暂未开放");
				break;
			case 2:
				BaseApp.showToast("暂未开放");
				break;
			}
			//System.out.println("下拉菜单点击" + position);
			popMenu.dismiss();
		}
	};

	ImageGetter imageGetter = new ImageGetter() {
		 @Override
		 public Drawable getDrawable(String filename) {
			 final String guid = Global.getFileNameNoEx(filename);
			 if (resGallery.getVisibility() == View.VISIBLE) {
				 int index = Global.getResIndex(guid);
				 int resid = R.drawable.res_0;
				 switch (index) {
				 case 1:
					 resid = R.drawable.res_1;
					 break;
				 case 2:
					 resid = R.drawable.res_2;
					 break;
				 case 3:
					 resid = R.drawable.res_3;
					 break;
				 case 4:
					 resid = R.drawable.res_4;
					 break;
				 case 5:
					 resid = R.drawable.res_5;
					 break;
				 case 6:
					 resid = R.drawable.res_6;
					 break;
				 case 7:
					 resid = R.drawable.res_7;
					 break;
				 case 8:
					 resid = R.drawable.res_8;
					 break;
				 case 9:
					 resid = R.drawable.res_9;
					 break;
			 	}
			 	Drawable d = getResources().getDrawable(resid);
			 	d.setBounds(0, 0, d.getIntrinsicWidth(), d .getIntrinsicHeight());
			 	return d;
			 } else {
				 // TODO
		    	if (!StringUtils.isNull(guid)) {
					Drawable cachedImage = Global.asyncImageLoader.loadDrawable(guid, 32, 32, new ImageCallback() {
							
						@Override
						public void imageLoaded(Drawable imageDrawable, String imageUrl) {
							updateNoteImage();
						}					
					});
					if (cachedImage == null) {
						Drawable d = getResources().getDrawable(R.drawable.ic_menu_sync);
						 d.setBounds(0, 0, d.getIntrinsicWidth(), d .getIntrinsicHeight());
						 return d;
					} else {
						return cachedImage;
					}
		    	} else if (!StringUtils.isNull(guid) || Global.getResFileType(guid) == Global.RES_TYPE_SOUND) {
					 Drawable d = getResources().getDrawable(R.drawable.ic_audio);
					 d.setBounds(0, 0, d.getIntrinsicWidth(), d .getIntrinsicHeight());
					 return d;
		    	} else {
					 Drawable d = getResources().getDrawable(R.drawable.ic_menu_sync);
					 d.setBounds(0, 0, d.getIntrinsicWidth(), d .getIntrinsicHeight());
					 return d;
		    	}

			 }
//			 if (Global.getResFileType(filename) == Global.RES_TYPE_IMAGE) {
//				 String imgFile = Global.resDir + filename;
//				 Bitmap bitmap = ImageUtil.getImageThumbnail(imgFile, mNoteContentEdit.getWidth());
//				 Drawable d = new BitmapDrawable(bitmap);
//				 d.setBounds(0, 0, d.getIntrinsicWidth(), d .getIntrinsicHeight());
//				 return d;				 
//			 } else {
//				 Drawable d = getResources().getDrawable(R.drawable.ic_audio);
//				 d.setBounds(0, 0, d.getIntrinsicWidth(), d .getIntrinsicHeight());
//				 return d;				 
//
//			 }
		 }
	};
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	final class DemoJavaScriptInterface {
		DemoJavaScriptInterface() {
		}

		/**
		 * * This is not called on the UI thread. Post a runnable to invoke *
		 * loadUrl on the UI thread.
		 */
		public void clickOnAndroid() {
			handler.post(new Runnable() {
				public void run() {
					//mNoteContentView.loadUrl("javascript:toTest()");
				}
			});
		}
	}	
	
	public boolean onKeyDown(int keyCoder, KeyEvent event) {
		mNoteContentView.clearCache(true);
		mNoteContentView.loadUrl("file:///android_asset/ubbeditor/demo/index.html");
		
		return true;
		
		/*if (webView.canGoBack() && keyCoder == KeyEvent.KEYCODE_BACK) {
		// goBack()表示返回webView的上一页面
		webView.goBack(); 
		
		return true;
		}

		return false;*/
	}
	
	/**
	 * * Provides a hook for calling "alert" from javascript. Useful for *
	 * debugging your javascript.
	 */
	final class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			Log.d("ARCHERMIND", message);
			// webView.loadData(URLEncoder.encode(message, "UTF-8"), "text/html", "UTF-8"); 
			mNoteContentView.loadDataWithBaseURL ("file:///android_asset/ubbeditor/demo/index.html", message, "text/html", "UTF-8", "") ;
			result.confirm();
			return true;
		}
	}	


	private class SaveNoteTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {	
			NoteService noteSrvc = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
			if (noteSrvc != null) {
				noteSrvc.saveNote(note);
				
				if (!StringUtils.isNull(tagGuid)) {
					TagService tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");
					tagSrv.addNoteTag(note.getGuid(), tagGuid);
				}
			}

			return "";
		}

		@Override
		public void onPostExecute(String Re) {
		}
	}

	//
	private class GetAddressTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... arg0) {
			GetGpsInfo();
			if (latitude != 0.0 || longitude != 0.0) {
				mMKSearch.reverseGeocode(new GeoPoint((int)latitude, (int)longitude));
			}
			
			return null;
		}
		
		@Override
		protected void onPreExecute() {
		}

		@Override
		public void onPostExecute(String Re) {
			if (latitude != 0.0 || longitude != 0.0) {
				String title = mNotetitle.getText().toString();
				if (title.equals("") && !address.equals("")) {
					mNotetitle.setHint(address);
				}
			}
			
		}
	};
	public void GetGpsInfo() {
		
		//获取经纬度 
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
		if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if(location != null) {
				latitude = location.getLatitude(); //经度 
				longitude = location.getLongitude(); //纬度 
			}
		} else {
			LocationListener locationListener = new LocationListener() {
				@Override
				public void onLocationChanged(Location location) { //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发 
					if (location != null) { 
						Log.i("SuperMap", "Location changed : Lat: " 
								+ location.getLatitude() + " Lng: " 
								+ location.getLongitude()); 
					} 
				} 
				@Override
				public void onProviderDisabled(String provider) { 
					// Provider被disable时触发此函数，比如GPS被关闭 
				}
				@Override
				public void onProviderEnabled(String provider) { 
					// Provider被enable时触发此函数，比如GPS被打开 
				} 
				@Override
				public void onStatusChanged(String provider, int status, Bundle extras) { 
					// Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数 
				}
			};
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 0,locationListener); 
			Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
			if(location != null){
				latitude = location.getLatitude(); //经度 
				longitude = location.getLongitude(); //纬度 
			}
		}
	}

	/** 
     * 内部类实现MKSearchListener接口,用于实现异步搜索服务 
     *  
     * @author liufeng 
     */  
    public class MySearchListener implements MKSearchListener {  
        /** 
         * 根据经纬度搜索地址信息结果 
         *  
         * @param result 搜索结果 
         * @param iError 错误号（0表示正确返回） 
         */  
        @Override  
        public void onGetAddrResult(MKAddrInfo result, int iError) {  
            if (result == null) {  
                return;  
            }  
            StringBuffer sb = new StringBuffer();  
            // 经纬度所对应的位置  
            sb.append(result.strAddr).append("/n");  
  
            // 判断该地址附近是否有POI（Point of Interest,即兴趣点）  
            if (null != result.poiList) {  
                // 遍历所有的兴趣点信息  
                for (MKPoiInfo poiInfo : result.poiList) {  
                    //sb.append("----------------------------------------").append("/n");  
                    sb.append(poiInfo.name).append(" ");  
                    sb.append(poiInfo.address);  
//                    sb.append("经度：").append(poiInfo.pt.getLongitudeE6() / 1000000.0f).append("/n");  
//                    sb.append("纬度：").append(poiInfo.pt.getLatitudeE6() / 1000000.0f).append("/n");  
//                    sb.append("电话：").append(poiInfo.phoneNum).append("/n");  
//                    sb.append("邮编：").append(poiInfo.postCode).append("/n");  
//                    // poi类型，0：普通点，1：公交站，2：公交线路，3：地铁站，4：地铁线路  
//                    sb.append("类型：").append(poiInfo.ePoiType).append("/n");  
                    break;
                }  
            }  
            // 将地址信息、兴趣点信息显示在TextView上  
            address = sb.toString();
            //addressTextView.setText(sb.toString());  
        }  
  
        /** 
         * 驾车路线搜索结果 
         *  
         * @param result 搜索结果 
         * @param iError 错误号（0表示正确返回） 
         */  
        @Override  
        public void onGetDrivingRouteResult(MKDrivingRouteResult result, int iError) {  
        }  
  
        /** 
         * POI搜索结果（范围检索、城市POI检索、周边检索） 
         *  
         * @param result 搜索结果 
         * @param type 返回结果类型（11,12,21:poi列表 7:城市列表） 
         * @param iError 错误号（0表示正确返回） 
         */  
        @Override  
        public void onGetPoiResult(MKPoiResult result, int type, int iError) {  
        }  
  
        /** 
         * 公交换乘路线搜索结果 
         *  
         * @param result 搜索结果 
         * @param iError 错误号（0表示正确返回） 
         */  
        @Override  
        public void onGetTransitRouteResult(MKTransitRouteResult result, int iError) {  
        }  
  
        /** 
         * 步行路线搜索结果 
         *  
         * @param result 搜索结果 
         * @param iError 错误号（0表示正确返回） 
         */  
        @Override  
        public void onGetWalkingRouteResult(MKWalkingRouteResult result, int iError) {  
        }

		@Override
		public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onGetRGCShareUrlResult(String arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}  
    }  
    
    
    //定义继承BaseAdapter的匹配器
    public class ImageAdapter extends BaseAdapter {
   
    	//Item的修饰背景
    	int mGalleryItemBackground;
   
    	//上下文对象
    	private Context mContext;
   
    	//图片数组
    	private ArrayList<String> mResGuid;
    	
		class ResViewHolder {
			public ImageView res_img = null;
			public TextView  res_idx = null;
		}

   
    	//构造方法
    	public ImageAdapter(Context c, ArrayList<String> resGuids){
    		mContext = c;
    		mResGuid = resGuids;
    		
    		//读取styleable资源
    		TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
    		mGalleryItemBackground = a.getResourceId(
    		R.styleable.Gallery1_android_galleryItemBackground, 0);
    		a.recycle();   
    	}
   
    	public void setResource(ArrayList<String> resGuids) {
    		mResGuid = resGuids;
    	}
    	//返回项目数量
    	@Override
    	public int getCount() {
    		return mResGuid.size();
    	}
   
    	//返回项目
    	@Override
    	public Object getItem(int position) {
    		return position;
    	}
   
    	//返回项目Id
    	@Override
    	public long getItemId(int position) {
    		return position;
    	}
   
    	//返回视图
    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		ResViewHolder holder;
            if (convertView == null) {
                    holder = new ResViewHolder();
                    convertView = getLayoutInflater().inflate(R.layout.gallery_item, null);
                    holder.res_img = (ImageView) convertView.findViewById(R.id.res_img);
                    holder.res_idx = (TextView) convertView.findViewById(R.id.res_idx);
                    convertView.setTag(holder);
                    //convertView.setBackgroundResource(mGalleryItemBackground);
            } else {
                    holder = (ResViewHolder) convertView.getTag();
            }
            
            holder.res_idx.setText(Integer.toString(Global.getResIndex(mResGuid.get(position))));
            holder.res_img.setTag(mResGuid.get(position));
            final String resGuid = mResGuid.get(position);
    		if (!StringUtils.isNull(resGuid)) {
				Drawable cachedImage = Global.asyncImageLoader.loadDrawable(resGuid, 96, 96, new ImageCallback() {
					
					@Override
					public void imageLoaded(Drawable imageDrawable, String imageUrl) {
						ImageView imageViewByTag = (ImageView)resGallery.findViewWithTag(resGuid);
						if (imageViewByTag != null) {
							imageViewByTag.setImageDrawable(imageDrawable);
						}						
					}					
				});
				if (cachedImage == null) {
					holder.res_img.setImageResource(R.drawable.ic_menu_sync);
				} else {
					holder.res_img.setImageDrawable(cachedImage);
				}
    		} else if (!StringUtils.isNull(resGuid) || Global.getResFileType(resGuid) == Global.RES_TYPE_SOUND) {
    			holder.res_img.setImageResource(R.drawable.ic_audio);
    		} else {
    			holder.res_img.setImageResource(R.drawable.ic_menu_sync);
    		}
            return convertView;
    	}
    }
}
